package com.scy.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.fasterxml.jackson.databind.type.LogicalType.DateTime;

/**
 * 本类用来演示
 *
 * @author wwh
 * @date 2024/7/4 23:09 $
 */
public class JWTUtils {

    private static final String jwtToken ="asjkdwkj&*^^%$*&(";
    /**
     * 私钥加密token
     * @param map 载荷中的数据
     * @param key 密钥
     * @param expireMinutes 过期时间，单位秒
     * @return
     * @throws Exception
     */
    public static String generateToken(Map<String, Object> map, PrivateKey key, int expireMinutes) throws Exception {



        /*真正的数据,载荷{json}*/
        /*加密方式,密钥...*/
        /*过期时间*/
        return Jwts.builder()
                .setClaims(map)//body数据,唯一的
                .signWith(SignatureAlgorithm.HS256,jwtToken )//签发算法,密钥为key
                .setIssuedAt(new Date())//设置签发时间
                .setExpiration(new Date(System.currentTimeMillis()+expireMinutes))//有效时间
                .compact();//生成String token
    }

    /** * 公钥解析token * * @param token 用户请求中的token * @return * @throws Exception */
    private static Jws<Claims> parserToken(String token, PublicKey key) {

        return Jwts.parser().setSigningKey(jwtToken).parseClaimsJws(token);
    }

    /** * 获取token中的用户信息 * * @param token 用户请求中的令牌 * @return 用户信息 * @throws Exception */
    public static Map<String, Object> getInfoFromToken(String token, PublicKey key) throws Exception {

//        Jwts.parser().setSigningKey(jwtToken).parseClaimsJws(token);
        Jws<Claims> claimsJws = parserToken(token, key);
        return claimsJws.getBody();
    }

    public static void main(String[] args) throws Exception {

        HashMap<String, Object> map = new HashMap<>();

        map.put("username","小明");
        map.put("introduce","是一个帅哥");
        String token = generateToken(map, null, 1000 * 60 * 60 * 60 * 24);
        System.out.println(token);
        /*
        * eyJhbGciOiJIUzI1NiJ9.
        * eyJpbnRyb2R1Y2UiOiLmmK_kuIDkuKrluIXlk6UiLCJleHAiOjE3MjEwMzMxMTgsImlhdCI6MTcyMDE0NDA4NiwidXNlcm5hbWUiOiLlsI_mmI4ifQ.
        * oPg7o-YRQlcqkRi5VcuXBmcPZFWo2UqvK8Ax3lkLYsc
        *
        * */


        Map<String, Object> info = getInfoFromToken(token, null);

        System.out.println(info.get("username"));
        System.out.println(info.get("introduce"));

    }


}
